<?php
namespace app\models\events;

use app\models\UploadForm;
use yii\db\ActiveRecord;
use yii\base\Behavior;

class UploadEvent extends Behavior
{
    public $changeAttribute;

    /**
     * 初始化
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        //不跳过更新
        if($this->changeAttribute === null)
        {
            $this->changeAttribute = 'src';
        }
    }

    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
            ActiveRecord::EVENT_BEFORE_DELETE=>'beforeDelete',
        ];
    }

    protected function deleteFile($skip)
    {
        $changeAttribute = $this->changeAttribute;
        if(is_array($changeAttribute)){
            foreach($changeAttribute as $attr){
                $this->deleteOne($attr,$skip);
            }
        }else{
            $this->deleteOne($changeAttribute,$skip);
        }
    }

    /**
     * @param $attr
     */
    protected function deleteOne($attr,$skip){
        $path = UploadForm::FILE_DIR;
        /* @var $owner ActiveRecord */
        $owner = $this->owner;
        $new_file_name = $owner->$attr;
        $file_name = $owner->getOldAttribute($attr);
        if(!$skip||($new_file_name!=$file_name)){
            if(($file_name!=='')&&(file_exists($path.$file_name))){
                unlink($path.$file_name);
            }
        }
    }

    /**
     * @param $event
     * @return bool
     */
    public function beforeUpdate($event)
    {
        $this->deleteFile(true);
        return true;
    }

    public function beforeDelete($event)
    {
        $this->deleteFile(false);
        return true;
    }
}